package retrofit2.converter.gson;

import org.json.JSONObject;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.converter.gson.adapter.ResponseAdapter;

public class JoyrunResponseBodyConverter<T> implements Converter<ResponseBody, T> {

	private final ResponseAdapter<T> adapter;

	/** json数据字段名 */
	private String name = "data";

	public JoyrunResponseBodyConverter(ResponseAdapter<T> adapter) {
		this.adapter = adapter;
	}

	public JoyrunResponseBodyConverter(ResponseAdapter<T> adapter, String name) {
		this.adapter = adapter;
		this.name = name;
	}

	@Override
	public T convert(ResponseBody value) throws IOException {
		try {
			String body = value.string();

			JSONObject json = new JSONObject(body);

			// 这里ret==0，如果ret!=0，在ErrorHandleInterceptor已经抛出错误了
			int    ret = json.optInt("ret");
			String msg = json.optString("msg", "");

			if (json.has(name)) {
				Object data = json.get(name);// data可能是JSONObject、JSONArray、String、int等

				body = data.toString();

				return adapter.fromJson(body);
			} else {
				throw new RuntimeException("json数据中不存在" + name + "字段");
			}
		} finally {
			value.close();
		}
	}
}
